package hars

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"post-stickers/catch"
	"post-stickers/models"
	"post-stickers/pkg"
	"time"
)

func Login(c *gin.Context) {
	name := c.PostForm("name")
	password := c.PostForm("password")
	if name == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户名和密码不能为空",
			"data": nil,
		})
		return
	}
	redis_login := "redis_login" + name
	catchcount, _ := catch.Rdb.Get(catch.Ctx, redis_login).Int()
	if catchcount > 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误3次,禁止登录",
			"data": nil,
		})
		return
	}

	var user models.User
	err := models.DB.Where("name = ?", name).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户名不正确",
			"data": nil,
		})
		return
	}
	if user.Password != pkg.Md5(password) {
		catch.Rdb.Incr(catch.Ctx, redis_login)
		if catchcount == 2 {
			catch.Rdb.Set(catch.Ctx, redis_login, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误3次,封禁2小时",
				"data": nil,
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
			"data": nil,
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": user,
	})

}
func List(c *gin.Context) {
	var post []models.Post

	redis_list := "redis_list"
	catchcount, _ := catch.Rdb.Get(catch.Ctx, redis_list).Result()
	if catchcount == "" {
		models.DB.Find(&post)
		jsondata, _ := json.Marshal(&post)
		catch.Rdb.Set(catch.Ctx, redis_list, jsondata, time.Hour*2)
	} else {
		json.Unmarshal([]byte(catchcount), &post)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": post,
	})
	return

}
func Limit(c *gin.Context) {
	id := c.Query("id")
	var post models.Post
	models.DB.Where("id = ?", id).First(&post)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询详情成功",
		"data": post,
	})
	return

}
